<template>
	<view class="app">
		<u-row justify="center"><u--image :showLoading="true" height="350rpx" width="350rpx" src="/static/logo.png" mode="widthFix"></u--image></u-row>
		<u-cell :border="false" title=" "></u-cell>
		<u-cell :border="false" title=" "></u-cell>
		<u-cell :border="false" title=" "></u-cell>
		<view class="Btn u-m-t-50">
			<!-- <input v-if="!isAccount" class="Btn_input" type="text" v-model:value="phoneNumber" placeholder="输入手机号" placeholder-style="text-align: center;"/> -->
			<input v-if="isAccount" class="Btn_input" type="number" v-model:value="phoneNumber" placeholder="输入手机号" placeholder-style="text-align: center;" />
			<input v-if="isAccount" class="Btn_input" type="text" v-model:value="password" placeholder="输入密码" placeholder-style="text-align: center;" />
		</view>

		<!-- #ifdef H5 -->
		<u-row>
			<u-col span="10" offset="1"><u-button type="primary" shape="circle" text="账号密码登录" @click="loginByAcc"></u-button></u-col>
		</u-row>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<u-row>
			<u-col span="10" offset="1"><u-button type="primary" shape="circle" :text="isAccount ? '登录' : '一键登录'" @click="submitlogin()"></u-button></u-col>
		</u-row>
		<!-- #endif -->

		<u-row>
			<u-col span="10" offset="1">
				<!-- #ifdef MP-WEIXIN -->
				<!-- <u-button type="primary" open-type="getPhoneNumber" @getphonenumber="submitlogin" shape="circle"
					text="微信授权登录"></u-button> -->
				<u-button class="bottom" type="primary" shape="circle" @click="submitlogin">授权登录</u-button>
				<!-- #endif -->
			</u-col>
		</u-row>
		<u-cell :border="false" title=" "></u-cell>
		<!-- <u-row>
			<u-col span="4" offset="4" class="u-m-t-20">
				<u-button type="info" shape="circle" text="其他登录方式" size="small" @click="loginBycode"></u-button>
			</u-col>
		</u-row> -->
		<!-- <u-popup border-radius="10" v-model="show"
		@close="close" @open="open" :mode="mode" 
		length="50%" :mask="mask"
		:closeable="closeable"
		:close-icon-pos="closeIconPos"
	>
		
	</u-popup> -->
		<u-overlay :show="tologin" @click="show = false"><u-toast ref="uToast"></u-toast></u-overlay>
	</view>
</template>

<script>
var that;

var UserInfo = require('../../../service/UserInfo.js'),
	mUserInfo;
	import mInit from "../../../tools/Init"
import { checkStr } from '@/common/js/util';
import WXBizDataCrypt from '../../../tools/WXBizDataCrypt.js';
// import loginMpWx from './mixin/login-mp-wx.js'
// import loginAppWx from './mixin/login-app-wx.js'
// import loginApple from './mixin/login-apple.js'
export default {
	// mixins: [loginMpWx, loginAppWx, loginApple],
	data() {
		return {
			tologin: false,
			logWay: 0,
			size: 34,
			wrap: false,
			width: 'auto',
			max: 3,
			activeColor: '#7468BE',
			checked: false,
			password: '0987654321',
			isAccount: false,
			show: false,
			mode: 'bottom',
			mask: true, // 是否显示遮罩
			closeable: true,
			closeIconPos: 'top-right',
			autoStatus: true,
			sessionKey: '',
			appID: 'wxf679991a6d85beb2',
			appSecret: 'f22849834ba1d96f7bb11813ac09fbe0',
			openId: '',
			session_key: '',
			phoneNumber: '',
			sharedId: '', //邀请人的id
			real_name: '新用户',
			isLoginPage: true
		};
	},
	onLoad(option) {
		that = this;
		if (option.id) {
			that.sharedId = id; //获取邀请id
		}
		mInit.init(this.mNetTool, res => {
			let userInfo = uni.getStorageSync('userInfo')
			if(userInfo){
				that.userInfo = userInfo
			}
			 
			this.loadData();
		})  
		that.show = true;
		mUserInfo = new UserInfo(this.mNetTool);
		// #ifdef APP-PLUS

		this.isAutoLogin();
		// #endif
		// #ifdef MP-WEIXIN
		// uni.login({
		//     provider:'weixin',
		//     success(data) {
		//         console.log(data);
		//         const code = data.code
		//     },
		//     fail(err) {
		//         console.log(err);
		//     }
		// })
		// #endif
	},
	mounted() {
		// #ifdef APP-PLUS
		that.logWay = 1;
		// #endif
		// #ifdef MP-WEIXIN
		that.logWay = 0;

		// #endif
	},
	methods: {
		loadData(){},
		loginBycode() {
			uni.navigateTo({
				url: 'login'
			});
		},
		checkboxChange(e) {
			that.checked = e.value;
			console.log(that.checked, e);
			console.log(e.value);
		},
		loginSuccessCallBack(data) {
			this.$util.msg('登陆成功');
			this.$store.commit('setToken', data);
			uni.switchTab({
				url: '../home/home'
			});
			console.log('logsucess');
		},
		// 判断是否支持一键登陆
		isAutoLogin() {
			let _that = this;
			uni.getProvider({
				//获取可用的服务提供商
				service: 'oauth',
				success: function(res) {
					console.log(res.provider); // ['weixin', qq', 'univerify']
				}
			});
			uni.preLogin({
				//预登录
				provider: 'univerify', //用手机号登录
				success() {
					_that.autoStatus = true;
					console.log('预登录成功');
				},

				fail(err) {
					//预登录失败
					_that.autoStatus = false;
					uni.navigateTo({
						url: './keyLogin'
					});
					console.log('错误码：' + err.errCode);
					console.log(err.errMsg);
				}
			});
		},
		loginByAcc() {
			uni.navigateTo({
				url: 'keyLogin'
			});
		},
		submitlogin(e) {
			// that.tologin = true;
			// this.$refs.uToast.show({
			// 	type: 'loading',
			// 	title: '正在登录',
			// 	message: '正在登录',
			// 	duration: '10000'
			// });
			console.log('用于完善用户信息')
			var promiss = new Promise((resolve, reject) => {
				// app端
				// #ifdef APP-PLUS
				//一键登录
				uni.login({
					//正式登录，弹出授权窗
					provider: 'univerify',
					univerifyStyle: {
						// 自定义登录框样式
						fullScreen: true, // 是否全屏显示，true表示全屏模式，false表示非全屏模式，默认值为false。
						backgroundColor: '#ffffff', // 授权页面背景颜色，默认值：#ffffff
						phoneNum: {
							color: '#2281F5' // 手机号文字颜色 默认值：#000000
						},
						icon: {
							path: 'static/uview/common/logo.png' // 自定义显示在授权框中的logo，仅支持本地图片 默认显示App logo
						},
						authButton: {
							normalColor: '#3479f5', // 授权按钮正常状态背景颜色 默认值：#3479f5
							highlightColor: '#2861c5', // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
							disabledColor: '#73aaf5', // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
							textColor: '#ffffff', // 授权按钮文字颜色 默认值：#ffffff
							title: '本机号码一键登录' // 授权按钮文案 默认值：“本机号码一键登录”
						}
					},
					success(res) {
						// 正式登录成功
						console.log('正式登录成功');
						console.log(res.authResult); // {openid:'登录授权唯一标识',access_token:'接口返回的 token'}
						let token = res.authResult.access_token;
						// 在得到access_token后，通过callfunction调用云函数
						uniCloud.callFunction({
							name: 'getPhoneNumber', // 云函数名称
							data: {
								//传给云函数的参数
								access_token: res.authResult.access_token, // 客户端一键登录接口返回的access_token
								openid: res.authResult.openid // 客户端一键登录接口返回的openid
							},
							success(callRes) {
								console.log(12313333333);
								that.phoneNumber = callRes.result.phoneNumber;
								uni.closeAuthView(); //关闭一键登录弹出窗口
								uni.showLoading({
									title: '登录中...'
								});
								resolve();
							},
							fail(callErr) {
								console.log(222222222222222222);
								reject();
							},
							complete() {
								console.log(1111111111111111);
								uni.closeAuthView(); //关闭授权登录界面
							}
						});
					},
					fail(err) {
						// 正式登录失败
						console.log(err.errCode);
						console.log(err.errMsg);
						uni.closeAuthView(); //关闭授权登录界面
					}
				});
				// #endif
				// #ifdef MP-WEIXIN

				let that = this;
				uni.showLoading({
					title:'登陆中'
				})
				wx.getUserProfile({
					desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: res => { 
						
						// userInfo: res.userInfo;
						let info = res.userInfo;
						console.log(info);	
						let userInfo = wx.getStorageSync('userInfo')
						
						console.log(  info.nickName ) 
						userInfo.avatar = info.avatarUrl;
						userInfo.real_name = info.nickName;
						//如果不存在flag就是新用户
						 if(!userInfo.wx_synchronization_flag){
							 let userInfo = uni.getStorageSync('userInfo') 
							 let date = new Date()
							 let year = date.getFullYear()
							 let month = date.getMonth() + 1
							 //现在的时间戳
							 let nowStamp = date.getTime()
							 //days获取这个月的天数
							 let days = new Date(year, month, 0).getDate()
							 
							 let next = 1000 * 60 * 60 * 24 * days
							 let expirationTime = new Date(nowStamp + next)
							 	userInfo.level = '-2';
							 	userInfo.vip_end_time = nowStamp + next;
							 	userInfo.vip_start_time = nowStamp;
						 }
						console.log(userInfo)  
							mUserInfo.update(
								{
									// mark: xxx
									id: wx.getStorageSync('user_id'),
									real_name: info.nickName,
									avatar: info.avatarUrl,
									wx_synchronization_flag: 1
								},
								() => {
									console.log('success')
									wx.setStorageSync('isLogin', true);
									 
									resolve();
									wx.showToast({
										title: '同步信息成功！',
										icon: 'succes',
										duration: 1000,
										mask: true
									});
								}
							);
							
					},
					fail() {
						uni.showToast({
							icon:"none",
							title:'用户拒绝获取'
						})
						reject();
					},
					complete() {}
				});
			
				// #endif
			});

			// 执行结果
			promiss.then(
				suc => {
					uni.showLoading({
						title: '登陆中'
					});
					// 成功
					that.tologin = false;
					// this.$refs.uToast.hide();
					let userInfo = uni.getStorageSync('userInfo');
					if(userInfo.level == -1 || !userInfo.level){
						uni.hideLoading();
						uni.navigateTo({
							url:'newUser'
						})
					}else{
						uni.hideLoading();
						wx.navigateBack({
							delta:10
						})
					}
					// let data = {
					// 	nick_name: that.real_name,
					// 	mobile: that.phoneNumber
					// };
					// let userid = {
					// 	real_name: userInfo.nick_name,
					// 	user_id: userInfo.user_id,
					// 	avatar: userInfo.avatar
					// };
					// console.log(userid);

					// mUserInfo.login(userid, res => {
					// 	console.log('111111111111', res);
					// 	if (res.login) {
					// 		uni.$u.toast('登录成功');
					// 		uni.hideLoading();
					// 		uni.navigateBack({
					// 			delta: 10
					// 		});
					// 		// uni.switchTab({
					// 		// 	url: '../home/home'
					// 		// })
					// 	} else {
					// 		uni.hideLoading();
					// 		uni.setStorageSync('isLogin', false);
					// 	}
					// });
				},
				err => {
					 
					uni.$u.toast('登录失败');
					uni.hideLoading();
				}
			);
			// return

			// promise.then(sucess => {
			// 	let data = {
			// 		mobile: that.phoneNumber,
			// 	}
			// 	mUserInfo.login(data, res => {

			// 		if (res.success) {
			// 			uni.$u.toast('登录成功')
			// 			uni.navigateBack({

			// 			})
			// 			uni.setStorageSync('userInfo', res.rows[0])
			// 			uni.setStorageSync('isLogin', true)
			// 		} else {
			// 			uni.setStorageSync('isLogin', false)
			// 		}

			// 	})
			// }, err => {
			// 	uni.$u.toast('登录失败，请联系客服')
			// })

			if (that.isAccount) {
				that.loginByPhon();
				return;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.app {
	width: 750rpx;

	height: 93vh;
	position: relative;
}

.loginWay {
	color: blue;
	text-align: center;
}

.log {
	width: 100%;
	text-align: center;

	image {
		margin: 0 auto;
		width: 400rpx;
		height: 400rpx;
	}

	margin-bottom: 80rpx;
}

.logItem {
	padding: 34rpx 34rpx 34rpx 34rpx;
	position: absolute;
	bottom: 0;
	width: 750rpx;
	height: 20%;
	// border-top: 4rpx solid $grey;

	.item {
		bottom: 0;
		border-top: 4rpx solid;
		display: flex;
		justify-content: space-between;
		width: 100%;
		height: 180rpx;
		align-items: center;

		image {
			width: 80rpx;
			height: 80rpx;
		}
	}
}

.Btn {
	.Btn_input {
		text-align: center;
		border: 1px solid;
		width: 600rpx;
		height: 90rpx;
		border-radius: 50rpx;
		margin: 40rpx auto;
	}

	.Btn_login {
		border: 1px solid;
		width: 600rpx;
		margin: 40rpx auto;
		height: 90rpx;
		border-radius: 50rpx;
		color: white;
	}
}
</style>
